<?php

namespace App\Models;

use Session;
use Cookie;

class Appointment extends BaseModel
{
    protected $table = "appointment";

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
 * 按条件查询全部数据,根据配置显示条数显示
 */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList1(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->with('card')->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    public function card()
    {
        return $this->hasOne('App\Models\Card', 'member_id', 'member_id');
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    public function getSnycOrderInfo($where)
    {
        return $this->multiWhere($where)->sharedLock()->get();
    }

    public function getCount($where)
    {
        return $this->multiWhere($where)->count();
    }

    /**
     * 获取预约info
     */
    public function getAppPointmentById($id)
    {
        $res = $this->getOne(array('id' => $id));
        if ($res) {
            $res = $res->toArray();
        }
        return $res;
    }

    /**
     * 添加预约第一步
     * @param $request
     * @return array
     */
    public function addAppPointmentStep1($request)
    {
        $data['user_id'] = $request['mid'];
        $data['member_id'] = $request['m_id'];
        $data['doctor_id'] = $request['d_id'];
        $doctor = new Doctor();
        $section = new Department();
        $d_info = $doctor->getOne(array('id' => $request['d_id']));

        if ($d_info) {
            $d_info = $d_info->toArray();
        }
        $sectioninfo = $section->getOne(array('id' => $d_info['section_id']));
        if ($sectioninfo) {
            $sectioninfo = $sectioninfo->toArray();
        }
        $data['doctor_name'] = $d_info['name'];
        $data['section_id'] = $d_info['section_id'];
        $data['section_name'] = $sectioninfo['department'];
        $data['mark_time'] = $request['mark_time'];
        $data['describe'] = $request['describe'];
        $data['register_price'] = 18;
        if ($request['pics']) {
            $imagePath = upImgs($data, 'pics');
            $data['imagePath'] = $imagePath;
        }
        addSession('appointment', $data);
        if (!session('appointment')) {
            return $res = ['state' => 0, 'msg' => '预约添加失败'];
        }
        return $res = ['state' => 1, 'msg' => '预约添加成功'];
    }


    /**
     * 添加预约第二步
     * @param $request
     * @return array
     */
    public function addAppPointmentStep2($request)
    {
        $doc = new Doctor();
        $member = new Member();
        $card = new Card();
        $doc_info = $doc->getDoctorById(array('id' => $request['d_id']));
        $card_info = $card->getOne(['member_id'=>$request['id'],'status'=>1]);
        $level = $card_info ? $card_info['level'] : 1;
        $price = apiCurl('regFee', array('id' => $doc_info['data']['id'], 'type' => $level));
        $member = $member->getMemberById($request);
        $data['doctor'] = $doc_info;
        $data['doctor']['data']['free'] = $price['Fee'];
        $data['member'] = $member;
        return ['state' => 1, 'msg' => "ok", 'data' => $data];
    }

    /**
     * 检查该医生是否已被预约
     */
    public function checkHasApp($request)
    {
        $d_id = $request['d_id'];
        $mark = date('Y-m-d', strtotime("+" . $request['key'] . " day"));
        $mark_time = $mark . " " . $request['time'];
        if (empty($d_id) || empty($mark_time)) {
            return ['state' => 1, 'msg' => '参数错误'];
        }
        // 查询条件
        $where['mark_time'] = strtotime($mark_time);
        $where['doctor_id'] = $d_id;
        $where['status'] = array('in', array(0 => 0, 1 => 1));
        $has_reslut = $this->getOne($where);
        // 如果返回有值,代表已预约
        if ($has_reslut) {
            return ['state' => 0, 'msg' => "该时间段已被预约"];
        }
        return ['state' => 1, 'msg' => 'ok'];
    }

    /**
     * 检测用户是否绑卡
     */
    public function checkMemberCard($request)
    {
        // 判断是否绑定就诊卡
        $where['user_id'] = $request['mid'];
        $where['member_id'] = $request['m_id'];
        $card = new Card();
        $bind = $card->getOne($where);
        if (!$bind) {
            return ['state' => 2, 'msg' => "该就诊人未绑卡"];
        }
        return ['state' => 1, 'msg' => "ok"];
    }

    /**
     * 付款确认
     */
    public function getConfimPay($request)
    {
        $res = $this->getAppPointmentById($request['aid']);
        $nowdata = time();
        $remain = (strtotime($res['created_at']) + (15 * 60)) - $nowdata;
        $res['remain'] = $remain;
        // 判断该就诊人是否绑定就诊卡
        $u_where['user_id'] = $request['mid'];
        $u_where['member_id'] = $res['member_id'];
        $card = new Card();
        $has_card = $card->getOne($u_where);
        if ($has_card) {
            $res['is_card_pay'] = 1;
            // 读取就诊卡余额
            $res1 = apiCurl('memberAccountQuery', $has_card['card_no']);
            $res['money'] = 200;
        } else {
            $res['is_card_pay'] = 0;
        }
        return $res;
    }

    /**
     * 添加预约第三步
     * @param $request
     * @return array
     */
    public function addAppPointmentStep3($request)
    {
        $data['user_id'] = $request['mid'];
        $data['member_id'] = $request['m_id'];
        $data['doctor_id'] = $request['d_id'];
        $doctor = new Doctor();
        $section = new Depart();
        $member = new Member();
        $User = new User();
        // 验证是否该号是否是否已被预约
        $where['doctor_id'] = $request['d_id'];
        $where['member_id'] = $request['m_id'];
        $where['user_id'] = $request['mid'];
        $where['mark_time'] = strtotime($request['mark_time']);
        $app = $this->getOne($where);
        if($app){
            return ['state'=>0,'msg'=>"该号已被预约"];
        }

        $user_info = $User->getUserById(['id' => $request['mid']]);
        $d_info = $doctor->getOne(['id' => $request['d_id']]);
        $member_info = $member->getMemberById(['id' => $request['m_id']]);
        if ($d_info) {
            $d_info = $d_info->toArray();
        }
        $sectioninfo = $section->getOne(['id' => $d_info['depart_id']]);
        if ($sectioninfo) {
            $sectioninfo = $sectioninfo->toArray();
        }
        $data['order_no'] = createOrderNo();
        $data['doctor_name'] = $d_info['name'];
        $data['depart_id'] = $d_info['depart_id'];
        $data['depart_name'] = $sectioninfo['name'];
        $data['mark_time'] = strtotime($request['mark_time']);
        $data['addtime'] = time();
        $data['reffer_doc_id'] = $d_info['reffer_id'];
        $data['desc'] = $request['describe'];
        $data['created_at'] = date('Y-m-d H:i:s', time());
        $data['register_price'] = $request['money']; // 挂号费
        // 预约用户登记
//        $his_reg = apiCurl('userReg', array('openid' => $user_info['data']['openid'], 'name' => $member_info['data']['name'], 'sex' => $member_info['data']['sex'], 'age' => 20, 'mobile' => $member_info['data']['mobile'], 'id_card' => $member_info['data']['id_card']));
//        $SCA01 = $his_reg['SCA01'];
        // 进行预约用户登记
//        $resulte = apiCurl("orderReg", array('opid' => $user_info['data']['openid'], 'sc_id' => $SCA01, 's_id' => $sectioninfo['reffer_id'], 'd_id' => $d_info['reffer_id'], 'type' => 1, 'ampm' => 0, "b_time" => $request['mark_time'], 'e_time' => date("Y-m-d H:i:s", strtotime($request['mark_time']) + 30 * 60)));
        // 进行his_用户预约
        $his_res = apiCurl('reg', array('uid' => request('mid'), 'sca01' => $member_info['data']['reffer_id'], 'reffer_s_id' => $sectioninfo['reffer_id'], "reffer_d_id" => $d_info['reffer_id'], 'reg_type' => $d_info['reg_type'], 'reg_type_vip' => $d_info['reg_type_vip'], 'remark' => "22"));
        if (!isset($his_res['VAC01'])) {
            return $res = ['state' => 0, 'msg' => '预约订单添加失败'];
        }
        $data['reffer_id'] = $his_res['VAC01']; // 就诊号
//        $res = apiCurl('regPayCheck',$data);
//        if (!$res['Result']) {
//            return ['state' => 0, 'msg' => '预约订单金额不一致'];
//        }
        $res = $this->add($data);
        if (!$res) {
            return $res = ['state' => 0, 'msg' => '预约订单添加失败'];
        }
        return $res = ['state' => 1, 'msg' => '预约订单添加成功', 'aid' => $res];
    }

    /**
     * 添加预约
     * @param $request
     * @return array
     */
    public function addOrder($request)
    {
        tolog('队列执行顺序3：' . time());
        $data['user_id'] = $request['mid'];
        $data['member_id'] = $request['m_id'];
        $data['doctor_id'] = $request['d_id'];
        $doctor = new Doctor();
        $section = new Depart();
        $d_info = $doctor->getOne(array('id' => $request['d_id']));
        if ($d_info) {
            $d_info = $d_info->toArray();
        }
        $sectioninfo = $section->getOne(array('id' => $d_info['depart_id']));
        if ($sectioninfo) {
            $sectioninfo = $sectioninfo->toArray();
        }
        $data['order_no'] = createOrderNo();
        $data['doctor_name'] = $d_info['name'];
        $data['depart_id'] = $d_info['depart_id'];
        $data['depart_name'] = $sectioninfo['name'];
        $data['mark_time'] = strtotime($request['mark_time']);
        $data['addtime'] = time();
        $data['reffer_doc_id'] = $d_info['reffer_id'];
        $data['desc'] = $request['describe'];
        $data['created_at'] = date('Y-m-d H:i:s', time());
        $data['register_price'] = $request['money']; // 挂号费
        $this->add($data);


        $param['uid'] = $request['mid'];
        $param['reg_type_vip'] = $request['reg_type_vip'];
        $param['uid'] = $request['mid'];
        $param['uid'] = $request['mid'];
        $param['uid'] = $request['mid'];
        $param['uid'] = $request['mid'];
        $param['uid'] = $request['mid'];
        $param['uid'] = $request['mid'];
        $param['uid'] = $request['mid'];

        $result = apiCurl('reg', $data);

//        $user = new User();
//        $user = $user->getUserById(array('id' => $param['uid']));
//        if ($user['data']['group_id'] != 1) {
//            $horegtype = $param['reg_type_vip'];
//        } else {
//            $horegtype = $param['reg_type'];
//        }
//        $data['openid'] = $user['data']['openid'];
//        $data['sca01'] = $param['mid'];
//        $data['hodepid'] = $param['reffer_s_id'];
//        $data['hodocid'] = $param['reffer_d_id'];
//        $data['horegtype'] = $horegtype;
//        $data['regdate'] = date('Y-m-d H:i:s', time());
//        $data['remark'] = "微信在线挂号登记";

    }

    public function getAppointmentListAll($request)
    {
        $where = [];
        if ($request['keywords']) {
            if (is_numeric($request['keywords'])) {
                $where['id'] = $request['keywords'];
            } else {
                $where['doctor_name'] = ['like', '%' . $request['keywords'] . '%'];
            }
        }
        if ($request['status']) {
            $where['status'] = $request['status'];
        }
        $order['id'] = 'desc';
        $rows = $this->getList1($where,'*',$order,10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        $member = new Member();
        foreach ($rows['data'] as $key => $val) {
            $m_where['id'] = $val['member_id'];
            $m_info = $member->getOne($m_where);
            $rows['data'][$key]['name'] = $m_info['name'];
        }
        $res = ['state' => 0, 'msg' => 'ok', 'data' => $rows];
        return $res;
    }

    /**
     * 预约列表
     * @param $request
     * @return array
     */
    public function getAppointmentList($request)
    {
        $where['user_id'] = $request['mid'];
        if ($request['status']) {
            $where['status'] = $request['status'];
        } else {
            $where['status'] = 0;
        }
        if ($request['status'] == 0) {
            $order['created_at'] = 'desc';
        } else {
            $order['mark_time'] = 'asc';
        }
        $rows = $this->getList($where, '*', $order, 10);
        if ($rows) {
            $rows = $rows->toArray();
            $rows['pageNoList'] = getPageNoList($rows['last_page'], request('page', 1), 10);
        }
        $member = new Member();
        foreach ($rows['data'] as $key => $val) {
            $m_where['id'] = $val['member_id'];
            $m_info = $member->getOne($m_where);
            $rows['data'][$key]['date'] = date('Y-m-d H:i:s', $val['mark_time']);
            $rows['data'][$key]['name'] = $m_info['name'];
            if ($request['status'] == 0) {
                $nowdata = time();
                $remain = (strtotime($val['created_at']) + (15 * 60)) - $nowdata;
                $rows['data'][$key]['remain'] = $remain;
            }
            if ($request['status'] == 1) {
                $nowdata = time();
                $remain = $val['mark_time'] - $nowdata;
                $rows['data'][$key]['remain'] = $remain;
            }
            $rows['data'][$key]['address'] = "医院";
        }
        $res = ['state' => 0, 'msg' => 'ok', 'data' => $rows];
        return $res;
    }

    /**
     * 改签数据
     */
    public function getChangeTimes($request)
    {
        $appointent = $this->getAppPointmentById($request['id']);
        $doctor = new Doctor();
        $doctorlist = $doctor->getList(['depart_id' => $appointent['depart_id']]);
        if ($doctorlist) {
            $doctorlist = $doctorlist->toArray();
        }
        $data['aid'] = $appointent['id'];
        $data['doctorlist'] = $doctorlist;
        return $data;
    }

    /**
     * 检测同一天同一科室 ***用户是否预约
     */
    public function checkInDayBySection($request){
        $d_id = $request['d_id'];
        $m_id = $request['m_id'];
        $mark_time = $request['mark_time'];
        $date = explode(" ",$mark_time);
        $byStartTime = strtotime($date[0]." "."00:00:00") ; // 开始时间
        $byEndTime = strtotime($date[0]." "."12:00:00"); //结束时间

        $doctor = new Doctor();
        $doctor_info = $doctor->getDoctorById(array('id'=>$d_id));
        $where['mark_time'] = ['glt',[['>=',$byStartTime],['<=',$byEndTime]]]; // 同一天内
        $where['depart_id'] = $doctor_info['data']['depart_id']; // 同一科室
        $where['member_id'] = $m_id; // 同一人
        $res = $this->getOne($where);
        if($res){
            return ['state'=>0,'msg'=>'该就诊人该日期已预约了该科室的医师'];
        }
        return ['state'=>1,'ok'];
    }

    /**
     * 提交改签数据
     * @param $request
     * @return array
     */
    public function postChangeTimes($request)
    {
        $where['id'] = $request['aid'];
        $order = $this->getOne($where);
        if ($order['is_gq']) {
            return ['state' => 0, 'msg' => "请勿重复改签，预约只能改签一次"];
        }
        $mark_time = strtotime($request['mark_time']);
        $condition['doctor_id'] = $request['d_id'];
        $condition['depart_id'] = $order['depart_id'];
        $condition['mark_time'] = $mark_time;
        $condition['status'] = 1;
        $neworder = $this->getOne($condition);
        if ($neworder) {
            return ['state' => 0, 'msg' => "改签失败，该科室医生该时段已被预约"];
        }
        $doctor = new Doctor();
        $docInfo = $doctor->getOne(['id'=>$request['d_id']]);
        $updata['doctor_id'] = $request['d_id'];
        $updata['doctor_name'] = $docInfo['name'];
        $updata['mark_time'] = $mark_time;
        $updata['is_gq'] = 1;
        $this->start();
        try {

            $res = $this->up($where, $updata);
            $params['id'] = $request['aid'];
            $params['time'] = $request['mark_time'];
            $result = apiCurl('regChange', $params);
            if ($res && $result['result']) {
                $this->commit();
                //短信类型:1预约成功,2绑定就诊人,3改签,4充值成功 5.绑定就诊卡
                $member = new Member();
                $memberInfo = $member->getOne(['id' => $order['member_id']]);
                $sms = new SmsLog();
                $sms->sendCaptcha($memberInfo['mobile'],3);
                return ['state' => 1, 'msg' => "改签成功"];
            }
        } catch (\Exception $e) {
            $this->rollBack();
            return ['state' => 0, 'msg' => "改签失败"];
        }
    }

    /**
     * 删除订单
     * @param $request
     * @return array
     */
    public function delOrder($id)
    {
        $where['id'] = $id;
        $res = $this->del($where);
        if (!$res) {
            return ['state' => 0, 'msg' => '订单删除失败'];
        }
        return ['state' => 1, 'msg' => '订单删除成功'];
    }

    /**
     * 改变预约状态
     */
    public function getChangeState($request, $msg = '')
    {
        $updata['status'] = $request['state'];
        $where['id'] = $request['a_id'];
        $res = $this->up($where, $updata);
        if (empty($msg)) {
            $msg = "订单支付";
        }
        if (!$res) {
            return ['state' => 0, 'msg' => $msg . '失败'];
        }
        return ['state' => 1, 'msg' => $msg . '成功'];
    }

    /**
     * 改变预约状态
     */
    public function dealOrder($order)
    {
        $this->start();
        try {
            $updata['status'] = 1;
            $updata['pay_time'] = time();
            $where['id'] = $order['id'];

            $this->up($where, $updata);
            $result = apiCurl('regPaybyCoupon', $order['id']);
            if (!$result['Result']) {
                apiCurl('regPaybyCoupon', $order['id']);
            }
            $payLog = new PayLog();
            $payLog->addPayLog($order['user_id'], 1, $order['id']);
            $this->commit();
            $member = new Member();
            $memberInfo = $member->getOne(['id' => $order['member_id']]);
            $sms = new SmsLog();
            //短信类型:1预约成功,2绑定就诊人,3改签,4充值成功
            $sms->sendCaptcha($memberInfo['mobile'], 1, $order);
            return true;
        } catch (\Exception $e) {
            $this->rollBack();
            return false;
        }
    }

    /**
     * 改变预约状态
     */
    public function dealCardOrder($order)
    {
        $this->start();
        try {
            $updata['status'] = 1;
            $updata['pay_time'] = time();
            $where['id'] = $order['id'];

            $this->up($where, $updata);
//            $result = apiCurl('regPaybyCoupon', $order['id']);
//            if (!$result['result']) {
//                apiCurl('regPaybyCoupon', $order['id']);
//            }
            $payLog = new PayLog();
            $payLog->addPayLog($order['user_id'], 1, $order['id']);
            $this->commit();
            $member = new Member();
            $memberInfo = $member->getOne(['id' => $order['member_id']]);
//            $sms = new SmsLog();
//            //短信类型:1预约成功,2绑定就诊人,3改签,4充值成功
//            $sms->sendCaptcha($memberInfo['mobile'], 1, $order);
            return true;
        } catch (\Exception $e) {
            $this->rollBack();
            return false;
        }
    }

    public function dealOrder1($id)
    {
        $this->start();
        try {
            $updata['status'] = 1;
            $updata['pay_time'] = time();
            $where['id'] = $id;

            $this->up($where, $updata);
//            $result = apiCurl('regPay', $id);
//            if (!$result['result']) {
//                apiCurl('regPay', $id);
//            }
            $payLog = new PayLog();
            $payLog->addPayLog(1, 1, $id);
            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->rollBack();
            return false;
        }
    }

    /**
     * 预约时间修改
     * scf01 预约id
     * scf10 预约时间
     * remark 备注
     * BCE01A 更换后医生id
     * BCK01A 更换后科室ID
     * @result
     * Result 1 成功  0 失败
     */
    public function his_order_update($params)
    {
        $appoinment = $this->getOne(['id' => $params['aid']]);
        $depart = new Depart();
        $section = $depart->getDepartInfoById($appoinment['depart_id']);
        $data['scf01'] = $appoinment['reffer_id'];
        $data['scf10'] = $params['time'];
        $data['remark'] = '微信在线改签';
        $data['BCE01A'] = $appoinment['reffer_doc_id'];
        $data['BCK01A'] = $section['reffer_id'];
        return $data;
    }

    /**
     * 判断是否预约
     * @param
     * bck01 int 科室id
     * bce01 int 医生id
     * scf10 string 预约时间 yyyy-mm-dd HH:mm:ss
     * @result array
     * Result int 0没有预约  >1已经预约
     */
    public function his_get_appointment_count($params)
    {
//        $appoinment = $this->getOne(['id'=>$params['appoinment_id']]);
        $data['bck01'] = $params['depart_id'];
        $data['bce01'] = $params['doctor_id'];
        $data['scf10'] = $params['time'];
        return $data;
    }

    public function his_order_cancel($scf01, $remark)
    {
        $data['scf01'] = $scf01;
        $data['remark'] = $remark;
        return $data;
    }

    /**
     * 预约登记
     * @param $openid  string 微信openid 没有可以使用 就诊人id拼接 "bdx".sprintf('%07s', $patientid);
     * @param $sca01   int crm客人id
     * @param $hodepid int his科室id
     * @param $hodocid int his医生id
     * @param $type =0    int 预约类型0天1上午下午2精确到时间
     * @param $ampm =0   int 0上午1下午
     * @param $begintime string 预约时间开始 2016-01-06 09:00:00
     * @param $endtime   string 预约时间结束 2016-01-06 09:20:00
     * @param $remark    string 备注
     * @return array
    Result int 1成功0失败
     * Errmsg string 失败信息/错误原因
     * SCF01 int 预约ID
     * CRM客户ID
     * SCF04 String 预约号
     * 病人ID
     * */
    public function his_order_reg($params)
    {
        $data['openid'] = $params['opid'];
        $data['sca01'] = $params['sc_id'];
        $data['hodepid'] = $params['s_id'];
        $data['hodocid'] = $params['d_id'];
        $data['type'] = $params['type'];
        $data['ampm'] = $params['ampm'];
        $data['begintime'] = $params['b_time'];
        $data['endtime'] = $params['e_time'];
        $data['remark'] = "用户预约登记";
        return $data;
    }


    public function his_price_list($itype, $keywords)
    {
        $data['itype'] = $itype;
        $data['keywords'] = $keywords;
        return $data;
    }


    public function his_get_cardno($vaa01)
    {
        $data['vaa01'] = $vaa01;
        return $data;
    }

    public function his_inpt_list($vaa01)
    {
        $data['vaa01'] = $vaa01;
        return $data;
    }

    public function his_get_vaj($acf01, $vaa07, $bdate, $edate)
    {
        $data['acf01'] = $acf01;
        $data['vaa07'] = $vaa07;
        $data['bdate'] = $bdate;
        $data['edate'] = $edate;
        return $data;
    }


    public function his_get_vae($vaa01)
    {
        $data['vaa01'] = $vaa01;
        return $data;
    }


    public function his_get_lab($vbq01)
    {
        $data['vbq01'] = $vbq01;
        return $data;
    }


    public function his_get_vbl_member($vaa01)
    {
        $data['vaa01'] = $vaa01;
        return $data;
    }


    public function his_get_jzys($vac01)
    {
        $data['vac01'] = $vac01;
        return $data;
    }

    public function his_get_lineup_count($vac01, $vac02, $vaa01, $sca01)
    {
        $data['vac01'] = $vac01;
        $data['vac02'] = $vac02;
        $data['vaa01'] = $vaa01;
        $data['sca01'] = $sca01;
        return $data;
    }

    /**
     * 挂号、预约完诊状态  参数不使用，等于0
     * @param $vac01 int 挂号id
     * @param $scf01 int 预约id
     * return
     * Result = 1 表示已经完诊，可以进行评价
     *
     * 挂号未支付 result=0  当前挂号记录还未完成就诊
     *
     */
    public function his_reg_order_state($id)
    {
        $order = $this->getOne(['id' => $id]);
        $data['vac01'] = $order['reffer_id'];
        $data['scf01'] = 0;
        return $data;
    }

    public function his_get_vaa01($type, $cardno)
    {
        $data['type'] = $type;
        $data['cardno'] = $cardno;
        return $data;
    }

    public function his_lis_report($vaa01, $sca01, $cardno)
    {
        $data['vaa01'] = $vaa01;
        $data['sca01'] = $sca01;
        $data['cardno'] = $cardno;
        return $data;
    }

    /**
     * 挂号登记
     */
    public function his_reg($param)
    {
        $user = new User();
        $user = $user->getUserById(array('id' => $param['uid']));
        if ($user['data']['group_id'] != 1) {
            $horegtype = $param['reg_type_vip'];
        } else {
            $horegtype = $param['reg_type'];
        }
        $data['openid'] = $user['data']['openid'];
        $data['sca01'] = $param['sca01'];
        $data['hodepid'] = $param['reffer_s_id'];
        $data['hodocid'] = $param['reffer_d_id'];
        $data['horegtype'] = $horegtype;
        $data['regdate'] = date('Y-m-d H:i:s', time());
        $data['remark'] = "微信在线挂号登记";
        return $data;
    }

    /**
     * 挂号改签
     * @param $
     */
    public function his_reg_change($param)
    {
        $res = $this->getAppPointmentById($param['id']);
        $data['vac36'] = $param['time'];
        $data['vac01'] = $res['reffer_id'];
        $data['bce01a'] = $res['reffer_doc_id'];
        $data['bck01a'] = $res['doctor_name'];
        return $data;
    }


    public function updateOrder()
    {
        //status 支付状态：0.未支付 1.待就诊 2.待评价 3.已完成 4.已退款 5.已过期6.已取消
        //待就诊超时则逾期
        $condition['status'] = 1;
        $rows = $this->getList($condition);
        if ($rows) {
            foreach ($rows as $k => $v) {
                if ($v['reffer_id']) {
                    $res = apiCurl('regOrderState', $v['id']);
                    if ($res['result']) {
                        $this->up(['id' => $v['id']], ['status' => 2]);
                    } else {
                        if ($v['mark_time'] < time()) {
                            $this->up(['id' => $v['id']], ['status' => 5]);
                        }
                    }
                } else {
                    if ($v['mark_time'] < time()) {
                        $this->up(['id' => $v['id']], ['status' => 5]);
                    }
                }
            }
        }
    }

    /**
     * 订单统计
     */
    public function orderCount(){
        $doctor = new Doctor();
        $doctorlist  = $doctor->getList();
        foreach($doctorlist as $value){
             $where['doctor_id'] = $value['id'];
             $where['status'] = ['in',[1,2,3]];
             $order_num = $this->getCount($where);
             $updata['order_num'] = $order_num;
             $doctor->up(array('id'=>$value['id']),$updata);
        }
    }


    public function deleteOrder()
    {
        //status 支付状态：0.未支付 1.待就诊 2.待评价 3.已完成 4.已退款 5.已过期6.已取消
        //待支付订单超时则删除
        $setting = new Setting();
        $settingInfo = $setting->getSetting('system');
        $where['status'] = 0;
        $where['addtime'] = ['<', time() - $settingInfo['end_pay_time'] * 60];
        $this->up($where,['status'=>6]);
    }

    public function commentOrder()
    {
        //status 支付状态：0.未支付 1.待就诊 2.待评价 3.已完成 4.已退款 5.已过期6.已取消
        //待评价超时则自动好评并更新状态为已完成
        $term['status'] = 2;
        $term['mark_time'] = ['<', time() ];
        $rows = $this->getList($term);
        if ($rows) {
            foreach ($rows as $k => $v) {
                $data['user_id'] = $v['user_id'];
                $data['apponitment_id'] = $v['id'];
                $data['doctor_id'] = $v['doctor_id'];
                $data['point'] = 5;
                $data['status'] = 1;
                $data['content'] = '系统默认好评';
                $data['created_at'] = date('Y-m-d H:i:s', time());
                $comment = new Comment();
                $comment->add($data);
                $this->up(['id' => $v['id']], ['status' => 3]);
            }
        }
    }

}